package request;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 演示使用 request 对象获取 URL 的各个部分
 */
public class GetURL extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String schema = req.getScheme(); //获取协议名，http
        String serverName = req.getServerName(); //获取主机名，localhost
        int port = req.getServerPort(); //获取服务器端口号，8080
        String contextPath = req.getContextPath(); //获取项目名，/javaweb
        String servletPath = req.getServletPath(); //获取Servlet路径，/response/getURL
        String queryString = req.getQueryString(); //获取查询字符串, ?key=value
        String uri = req.getRequestURI();//获取请求URI，等于项目名+Servlet路径
        StringBuffer url = req.getRequestURL(); //获取请求URL，等于不包含参数的整个请求路径

        //todo 添加一个工具方法
        PrintWriter writer = resp.getWriter();
        write(writer, "schema", schema);
        write(writer, "serverName", serverName);
        write(writer, "port", port);
        write(writer, "contextPath", contextPath);
        write(writer, "servletPath", servletPath);
        write(writer, "queryString", queryString);
        write(writer, "uri", uri);
        write(writer, "url", url);
    }

    private void write(PrintWriter writer, String expression, Object result) {
        String RESULT_PRINT_FORMAT = "%1$-8s = %2$s%n";
        writer.printf(RESULT_PRINT_FORMAT, expression, result);
    }
}
